"""
@author: 李凌飞
@date: 2025-04-07
@description: 从json文件中制作映射文件json
@question:需要对文件进行按规则分类，按照要求制作映射文件json
"""
import json
import os
from typing import Dict

def create_name_filename_mapping(folder_path: str) -> Dict[str, str]:
    """
    创建姓名到文件名的映射字典
    
    :param folder_path: 包含JSON文件的文件夹路径
    :return: 字典{name: filename}
    """
    mapping = {}
    
    for filename in os.listdir(folder_path):
        if filename.endswith('.json'):
            filepath = os.path.join(folder_path, filename)
            
            try:
                with open(filepath, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                # 获取base_info中的name字段
                name = data.get('base_info', {}).get('name', '').strip()
                
                if name:  # 只有name存在时才添加到映射
                    mapping[name] = filename
                    
            except (json.JSONDecodeError, KeyError, AttributeError) as e:
                print(f"处理文件 {filename} 时出错: {str(e)}")
                continue
    
    return mapping

def save_mapping_to_json(mapping: Dict[str, str], output_path: str):
    """
    将映射保存为JSON文件
    
    :param mapping: 姓名到文件名的映射字典
    :param output_path: 输出JSON文件路径
    """
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(mapping, f, ensure_ascii=False, indent=2)

if __name__ == "__main__":
    # 输入文件夹路径
    input_folder = r"C:\Users\lenovo\Desktop\internal_partner_json"
    
    # 输出文件路径
    output_file = r"C:\Users\lenovo\Desktop\name_filename_mapping.json"
    
    # 创建映射
    name_mapping = create_name_filename_mapping(input_folder)
    
    # 保存到JSON文件
    save_mapping_to_json(name_mapping, output_file)
    
    print(f"成功创建映射文件，共 {len(name_mapping)} 条记录。")
    print(f"映射文件已保存到: {output_file}")